package com.hrt.manage.order.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.BackGoods;
import com.hrt.bean.GiftInfor;
import com.hrt.bean.OrderDetail;
import com.hrt.bean.OrderInfor;
import com.hrt.bean.OrderStatus;
import com.hrt.bean.PayType;
import com.hrt.bean.SnCodeSequence;
import com.hrt.bean.StockDetail;
import com.hrt.bean.Stocks;
import com.hrt.manage.bkgoods.service.BackGoodsService;
import com.hrt.manage.member.service.HRTMemberService;
import com.hrt.manage.order.service.OrderDetailService;
import com.hrt.manage.order.service.OrderInforService;
import com.hrt.manage.product.service.GiftInforService;
import com.hrt.manage.sncode.service.SNCodeService;
import com.hrt.manage.stock.service.StockDetailService;
import com.hrt.manage.stock.service.StocksService;
import com.hrt.vo.BackGoodsVO;
import com.hrt.vo.OrderDetailVO;
import com.hrt.vo.OrderInforVO;
import com.hrt.vo.StockDetailVO;

@Controller
@RequestMapping("manage/order")
public class OrderInforController extends BaseController<OrderInfor> {
	@Autowired
	private OrderInforService orderInforService;
	@Autowired
	private HRTMemberService hrtMemberService;
	@Autowired
	private GiftInforService giftInforService;
	@Autowired
	private StocksService stocksService;
	@Autowired
	private StockDetailService stockDetailService;
	@Autowired
	private SNCodeService snCodeService;
	@Autowired
	private BackGoodsService backGoodsService;
	

	@Autowired
	private OrderDetailService orderDetailService;

	private List<Map<String, Object>> orderStatusList;
	private List<Map<String, Object>> typeList;
	public List<Map<String, Object>> getTypeList() {
		typeList = PayType.getTypeList();
		return typeList;
	}

	public void setTypeList(List<Map<String, Object>> typeList) {
		this.typeList = typeList;
	}
	public List<Map<String, Object>> getOrderStatusList() {
		orderStatusList = OrderStatus.getOrderStatusList();
		return orderStatusList;
	}

	public void setOrderStatusList(List<Map<String, Object>> orderStatusList) {
		this.orderStatusList = orderStatusList;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request) {
		Map resultMap = new HashMap();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);

		setTotalCount(orderInforService.totalCount());

		List<OrderInfor> resultList = orderInforService.queryByPage(
				getPageIndex(), getPageSize());
		setList(resultList);
		
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}
	
	/**
	 * 
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/list")
	public ModelAndView list(@RequestParam(value = "msg", required = false) String msg,HttpServletRequest request) {
		ModelAndView view = new ModelAndView();

		list = orderInforService.queryByPage(getPageIndex(), getPageSize());
		setTotalCount(orderInforService.totalCount());
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		this.orderStatusList = getOrderStatusList();
		this.typeList = getTypeList();
		view.addObject("orderStatusList", orderStatusList);
		view.addObject("typeList", typeList);
		view.addObject("pageResult", page);
		if(msg!=null){
			
			view.addObject("message", msg);
		}
		return view;

	}
	

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();

		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			orderInforService.deleteById(idArr);
			
			//此循环用来构造订单详情的id数组
			for(int i=0;i<idArr.length;i++){
				List<OrderDetail> details = orderDetailService.getOrderDetailByOrderId(idArr[i]);
				Long[] detaisID = new Long[details.size()];
				for(int j=0;j<details.size();j++){
					detaisID[j] = details.get(j).getId();
				}
				orderDetailService.deleteById(detaisID);
			}
			return idArr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("orderInfo") OrderInforVO orderInforVO,
			HttpServletRequest request, HttpServletResponse response) {
		
		System.out.println("save");
		System.out.println("orderInforVO----------"+orderInforVO.getSummery());
		System.out.println("orderInforVO:" + orderInforVO.getPostCode());
		orderInforVO.setIsdelete(0);
		orderInforVO.setStatus(0);
		orderInforVO.setOrderSource(1);
		orderInforVO.setSender("何人堂");
		orderInforVO.setCreateTime(this.orderInforService.getDate());
		List<OrderDetailVO> details = new ArrayList<OrderDetailVO>();  
			try {
				
				for(OrderDetailVO od:orderInforVO.getDetails()){
					od.setIsdelete(0);
					od.setCreateTime(this.orderInforService.getDate()
							);
					
					od.setCreator(this.getOnlineManager(request, response)
							.getLoginName());
					od.setEditor((this.getOnlineManager(request, response)
							.getLoginName()));
					od.setEditTime(this.orderInforService.getDate());
					details.add(od);
				}
				orderInforService.saveOrderInfor(orderInforVO, details);
				response.sendRedirect("list.do");
			} catch (IOException e) {
				e.printStackTrace();
			}
		
	}
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("orderInfo") OrderInforVO orderInforVO,
			HttpServletRequest request, HttpServletResponse response) {
		System.out.println("update");
		System.out.println("orderInforVO----------"+orderInforVO.getSummery());
		List<OrderDetailVO> details = new ArrayList<OrderDetailVO>();
			for(OrderDetailVO od:orderInforVO.getDetails()){
				if(od.getId()==null&&od.getGiftDetailId()!=null){
					
					od.setCreateTime(this.orderInforService.getDate()
							);
					od.setCreator(this.getOnlineManager(request, response)
							.getLoginName());
					od.setEditor((this.getOnlineManager(request, response)
							.getLoginName()));
					od.setEditTime(this.orderInforService.getDate());
					details.add(od);
				}
				if(od.getId()!=null&&od.getGiftDetailId()!=null){
					
					details.add(od);
				}
			}
		
		orderInforService.updateOrderInfor(orderInforVO, details);
		try {
			response.sendRedirect("list.do");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 退货
	 * @param orderInforVO
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/backGoods", method = RequestMethod.POST)
	public void backGoods(@ModelAttribute("orderInfo") OrderInforVO orderInforVO,
			HttpServletRequest request, HttpServletResponse response) {
		if(orderInforVO.getGoodsList().size()>0||orderInforVO.getGoodsList()!=null){
			for(BackGoodsVO bg:orderInforVO.getGoodsList()){
				try {
					BackGoods backGoods = new BackGoods();
					BeanUtils.copyProperties(backGoods, bg);
					OrderInfor orderInfor = orderInforService.getOrderByid(orderInforVO.getId());
					orderInfor.setStatus(new Integer(6));
					orderInforService.updateOrder(orderInfor);
					
					backGoodsService.saveBackGoods(backGoods);
					//生成退库单
					Stocks stocks = stocksService.outStockByOrder(orderInfor);
					String msg = null;
					if(stocks!=null){
						msg="success";
					}
					else{
						msg="fail";
					}
					response.sendRedirect("list.do?msg="+msg);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	/**
	 * 
	 * @param itemCondition
	 * @return
	 */

	@RequestMapping(value = "/queryGiftIds")
	@ResponseBody
	public Map queryGiftIds(
			@RequestParam(value = "condition") String itemCondition,
			HttpServletRequest request, HttpServletResponse response) {
		String condtionStr = null;
		List proList = new ArrayList();
		Map result = new HashMap();
		try {
			condtionStr = new String(itemCondition.getBytes("iso-8859-1"),
					"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (condtionStr != null && !"".equals(condtionStr)) {
			proList = giftInforService.queryGiftInfors(condtionStr);
		}

		result.put("result", proList);
		return result;
	}

	

	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(
			@RequestParam(value = "id", required = true) String orderId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (orderId != null && !"".equals(orderId)) {
			OrderInfor orderInfor = this.orderInforService
					.getOrderByid(new Long(orderId));
			if (orderInfor != null) {
				map = transBean2Map(orderInfor);
			}

		}
		return map;

	}
	/**
	 * 单独发货
	 * @param orderId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/sendGift")
	@ResponseBody
	public String sendGift(
			@RequestParam(value = "id", required = true) Long orderId,
			HttpServletRequest request, HttpServletResponse response) {
		
		
		if (orderId != null && !"".equals(orderId)) {
			OrderInfor orderInfor = this.orderInforService.getOrderByid(orderId);
			//订单出库
			Stocks stocks = stocksService.outStockByOrder(orderInfor);
			if(stocks!=null){
				orderInfor.setStatus(new Integer(2));
				orderInforService.updateOrder(orderInfor);
				return "success";
			}
		}
		return "fail";
		
	}

	
		/**
		 * 删除订单详情
		 * @param itemId
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping(value = "/delItemById")
		@ResponseBody
		public boolean delItemById(@RequestParam(value = "id", required = true) Long itemId,
				HttpServletRequest request, HttpServletResponse response) {

			Map<Object, Object> map = new HashMap<Object, Object>();
			if (itemId != null && !"".equals(itemId)) {
				
				if (itemId != null) {
					return orderDetailService.delItemById(itemId);
					
				}
				
			}
			return false;
		}
		/**
		 * 集体发货
		 * @param orderId
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping(value = "/sendGoods", method = RequestMethod.POST)
		public @ResponseBody Long[] sendGoods(
				@RequestParam(value = "ids", required = true) String ids,
				HttpServletResponse response) throws IOException {
			Long[] idArr = null;
			if (ids != null) {
				if (ids.indexOf(",") != -1) {
					String[] idStrs = ids.split(",");
					idArr = new Long[idStrs.length];
					for (int idx = 0; idx < idStrs.length; idx++) {
						idArr[idx] = Long.parseLong(idStrs[idx]);
					}
				} else {
					idArr = new Long[] { Long.parseLong(ids) };
				}

			}
			try {
				orderInforService.sendGoodsById(idArr);
				return idArr;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}

		}
		/**
		 * 退货
		 * @param orderId
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping(value = "/returnGoods", method = RequestMethod.POST)
		public @ResponseBody Long[] returnGoods(
				@RequestParam(value = "ids", required = true) String ids,
				HttpServletResponse response) throws IOException {
			Long[] idArr = null;
			if (ids != null) {
				if (ids.indexOf(",") != -1) {
					String[] idStrs = ids.split(",");
					idArr = new Long[idStrs.length];
					for (int idx = 0; idx < idStrs.length; idx++) {
						idArr[idx] = Long.parseLong(idStrs[idx]);
					}
				} else {
					idArr = new Long[] { Long.parseLong(ids) };
				}
				
			}
			try {
				orderInforService.returnGoodsById(idArr);
				return idArr;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			
		}
		/**
		 * 退款
		 * @param orderId
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping(value = "/returnMoney", method = RequestMethod.POST)
		public @ResponseBody Long[] returnMoney(
				@RequestParam(value = "ids", required = true) String ids,
				HttpServletResponse response) throws IOException {
			Long[] idArr = null;
			if (ids != null) {
				if (ids.indexOf(",") != -1) {
					String[] idStrs = ids.split(",");
					idArr = new Long[idStrs.length];
					for (int idx = 0; idx < idStrs.length; idx++) {
						idArr[idx] = Long.parseLong(idStrs[idx]);
					}
				} else {
					idArr = new Long[] { Long.parseLong(ids) };
				}
				
			}
			try {
				orderInforService.returnMoneyById(idArr);
				return idArr;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			
		}
		
		/**
		 * 多条件查询
		 * @param pageIndex
		 * @param pageSize
		 * @param statu
		 * @param startTime
		 * @param endTime
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping(value = "/queryByConditions", method = RequestMethod.POST)
		@ResponseBody
		public Map<String, Object> queryByConditions(
				@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
				@RequestParam(value = "pageSize", required = false) Integer pageSize,
				@RequestParam(value = "statu", required = false) Integer statu,
				@RequestParam(value = "startTime", required = false) String startTime,
				@RequestParam(value = "endTime", required = false) String endTime,
				HttpServletRequest request, HttpServletResponse response) {
			System.out.println("kkkkkkkkkkkkkk");
			System.out.println("startTime-------"+startTime.toString());
			Map<String, Object> resultMap = new HashMap<String, Object>();
			if (pageSize == null || "".equals(pageSize)) {
				pageSize = 30;
			}
			if (pageIndex == null || "".equals(pageIndex)) {
				pageIndex = 1;
			}
			setPageIndex(pageIndex);

			setPageSize(pageSize);
			
			List<OrderInfor> resultList = new ArrayList<OrderInfor>();
			if(statu!=-1||(startTime!=null&&endTime!=null)){
				if(statu==-1&&(startTime!=null&&endTime!=null)){
					//resultList= orderInforService.getOrderByTime(start,end);
					String sql = "select order from OrderInfor where order.createTime";
					//resultList = orderInforService.queryByPage(sql, pageIndex, pageSize);
				}
				else{
					//resultList= orderInforService.getOrderByAll(statu,startTime,endTime);
				}
			}
			
			setList(resultList);
			
			setTotalCount(new Long(resultList.size()));
			this.setPageCount(computePageCount(getTotalCount(), getPageSize()));

			page = this.getPage();

			resultMap.put("pageResult", page);
			return resultMap;
		}
		/**
		 * 根据条形码返回一个退货单实体
		 * @param snCode
		 * @param request
		 * @param response
		 * @return
		 */
		@RequestMapping(value = "/getSnCodeByCode")
		@ResponseBody
		public Map getSnCodeByCode(
				@RequestParam(value = "snCode", required = false) String snCode,
				@RequestParam(value = "orderId", required = true) Long orderId,
				HttpServletRequest request, HttpServletResponse response) {
			BackGoods bg = new BackGoods();
			
			bg.setOrderId(orderId);//订单id
			bg.setSnCode(snCode);//礼品规格条形码
			Map map = new HashMap();
			if (snCode != null && !"".equals(snCode)) {
				SnCodeSequence scs =snCodeService.getSnCodeByCode(snCode);//加载条形码实体
				StockDetailVO sd = stockDetailService.getDetailById(scs.getStkDeId());//加载出库详情实体
				GiftInfor gf = giftInforService.getById(sd.getProId());//加载礼品实体
				
				bg.setSnCodeId(scs.getId());//条形码id
				bg.setOrderDetailId(sd.getId());//订单详情id
				bg.setGiftDetailId(sd.getRuleId());//礼品规格id
				bg.setGiftDetailName(sd.getRuleName());//礼品规格名称
				bg.setSalePrice(sd.getSalePrice());//礼品规格价格
				bg.setGiftName(gf.getGiftName());//礼品名称
				bg.setGiftCode(gf.getGiftCode());//礼品编码
				if (bg != null) {
					map = transBean2Map(bg);
				}

			}
			return map;

		}
	

}
